package com.dailyplanner.mail.logic;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;

import com.globallogic.dailyplanner.dto.Mail;
import com.globallogic.dailyplanner.dto.MailStatusEnum;
import com.globallogic.dailyplanner.vo.JMSAnswerMessageVO;
import com.globallogic.dailyplanner.vo.JMSMessageVO;

@MessageDriven(mappedName="jms/DailyPlannerQueue")
public class MailReceiver implements MessageListener{
	
	@EJB
	private MailSender mailSender;
	
	@Resource(lookup="jms/DailyPlannerAswerQueue")
	private Queue statusQueue;
	
	@Resource(lookup="jms/DailyplannerFactory")
	private ConnectionFactory connectionFactory;

	public void onMessage(Message jmsMessage) {
		ObjectMessage objectMessage = (ObjectMessage) jmsMessage;
		try {
			JMSMessageVO jmsMessageVO = (JMSMessageVO) objectMessage.getObject();
			Mail mail = jmsMessageVO.getMail();
			for(String email : jmsMessageVO.getEmails()){
				MailStatusEnum status = mailSender.sendMessage(email, mail);
				JMSAnswerMessageVO answerMessageVO = new JMSAnswerMessageVO(email, mail.getId(), status);
				sendAnswerToQueue(answerMessageVO);
			}
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
	private void sendAnswerToQueue(JMSAnswerMessageVO answer) throws JMSException{
		Connection connection = connectionFactory.createConnection();
		Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
		MessageProducer producer = session.createProducer(statusQueue);
		ObjectMessage objectAnswerMessage = session.createObjectMessage(answer);
		producer.send(objectAnswerMessage);
	}

}
